<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="资产名称" prop="assetsName" >
        <el-input
            style="width: 200px"
          v-model="queryParams.assetsName"
          placeholder="请输入资产名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="资产型号" prop="model">
        <el-input
            style="width: 200px"
          v-model="queryParams.model"
          placeholder="请输入资产型号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['assetsin:assetsin:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5" v-hasRole="['admin']">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['assetsin:assetsin:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5" v-hasRole="['admin']">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['assetsin:assetsin:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5" v-hasRole="['admin']">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['assetsin:assetsin:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="assetsinList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" v-hasRole="['admin']"/>
      <el-table-column label="排序ID" align="center" prop="id" v-hasRole="['admin']"/>
      <el-table-column label="资产名称" align="center" prop="assetsName" width="150px">
      </el-table-column>
      <el-table-column label="资产型号" align="center" prop="model" width="150px"/>
      <el-table-column label="操作人" align="center" prop="userName" />
      <el-table-column label="入库数量" align="center" prop="num" />
      <el-table-column label="入库日期" align="center" prop="date" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.date, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="status" >
        <template #default="scope">
          <!--          <dict-tag :options="assets_review_status" :value="scope.row.status"/>-->
          <el-tag type="warning" size="small" effect="dark" v-if="scope.row.status===`0`">待审核</el-tag>
          <el-tag type="primary" size="small" effect="dark" v-if="scope.row.status===`1`">通过</el-tag>
          <el-tag type="danger" size="small" effect="dark" v-if="scope.row.status===`2`">拒绝</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注"  align="center" prop="comment" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150px">
        <template #default="scope" >
          <el-button link type="primary" icon="Edit" v-if="scope.row.status===`0`" @click="handleUpdate(scope.row)" v-hasPermi="['assetsin:assetsin:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" v-if="scope.row.status===`0`" @click="handleDelete(scope.row)" v-hasPermi="['assetsin:assetsin:remove']">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column label="审核" v-hasRole="['admin']" align="center" class-name="small-padding fixed-width" fixed="right" width="150px" >
        <template #default="scope">
          <el-tag link type="success" style="cursor: pointer" effect="dark" v-if="scope.row.status===`0`" @click="changeAssetsInStatus(scope.row,`通过`)">通过</el-tag>
          <el-tag link  type="danger"  style="cursor: pointer;margin-left: 3px" effect="dark" v-if="scope.row.status===`0`"  @click="changeAssetsInStatus(scope.row,`拒绝`)" >拒绝</el-tag>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改资产入库对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="assetsinRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="资产名称" prop="assetsName">
          <el-select style="width: 100%" v-model="form.assetsId">
            <el-option v-for="item in assetsList" :key="item.id" :value="item.id"
                       :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="资产型号" prop="model">
          <el-input v-model="form.model" placeholder="请输入资产型号" />
        </el-form-item>
<!--        <el-form-item label="操作人" prop="userName" >
          <el-select style="width: 100%" v-model="form.userId" disabled>
            <el-option v-for="item in userList" :key="item.id" :value="item.userId"
                       :label="item.userName"></el-option>
          </el-select>
        </el-form-item>-->
        <el-form-item label="入库数量" prop="num">
          <el-input-number :min="1" v-model="form.num" placeholder="请输入入库数量" />
        </el-form-item>
        <el-form-item label="入库日期" prop="date">
          <el-date-picker clearable
            v-model="form.date"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择入库日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="comment">
          <el-input type="textarea" rows="3" v-model="form.comment" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Assetsin">
import { listAssetsin, getAssetsin, delAssetsin, addAssetsin, updateAssetsin } from "@/api/assetsin/assetsin";
import {listAssets} from "@/api/assets/assets.js";
import {listUser} from "@/api/system/user.js";
import {ElMessageBox} from "element-plus";
import {updateReceive} from "@/api/receive/receive.js";

const { proxy } = getCurrentInstance();

const assetsinList = ref([]);
const assetsList = ref([]);
const userList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    assetsId: null,
    model: null,
  },
  rules: {
/*    assetsName:[{
      required: true,
      message: "资产名称不能为空",
      trigger: "blur"
    }],*/
  assetsId: [
      { required: true, message: "资产ID不能为空", trigger: "blur" }
    ],
    model: [
      { required: true, message: "资产型号不能为空", trigger: "blur" }
    ],
    userId: [
      { required: true, message: "操作人ID不能为空", trigger: "blur" }
    ],
    num: [
      { required: true, message: "入库数量不能为空", trigger: "blur" }
    ],
    date: [
      { required: true, message: "入库日期不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

//===============
function changeAssetsInStatus(row, status) {
  // 使用对象展开运算符进行深拷贝，更简洁且易于理解
  const formCopy = { ...row };

  // 设置 status 数值
  const statusMap = { '通过': 1, '拒绝': 2 };
  formCopy.status = statusMap[status] || null;

  ElMessageBox.confirm(`您确定${status}吗？`, '确认审核', {type: "warning"})
      .then(() => {
        return updateAssetsin(formCopy);
      })
      .then(() => {
        proxy.$modal.msgSuccess("审核成功");
        //open.value = false;
        getList();
      })
      .catch(error => {
        console.error('审核失败:', error);
        // 可以在这里添加错误提示给用户
      });
}


/** 查询资产入库列表 */
function getList() {
  loading.value = true;
  listAssetsin(queryParams.value).then(response => {
    assetsinList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
  //=======
  listAssets(null).then(response => {
    assetsList.value = response.rows;
    //total.value = response.total;
    loading.value = false;
  });
  listUser(null).then(response => {
    userList.value = response.rows;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    assetsId: null,
    model: null,
    userId: null,
    num: null,
    date: null,
    status: null,
    comment: null
  };
  proxy.resetForm("assetsinRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加资产入库";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getAssetsin(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改资产入库";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["assetsinRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateAssetsin(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addAssetsin(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除资产入库编号为"' + _ids + '"的数据项？').then(function() {
    return delAssetsin(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('assetsin/assetsin/export', {
    ...queryParams.value
  }, `assetsin_${new Date().getTime()}.xlsx`)
}

getList();
</script>
